/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.configurer.handler;

import com.arisgo.cloud.common.exception.CloudException;
import com.arisgo.cloud.web.utils.RequestUtil;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Date;
import java.util.Map;

/**
 * @author Arisgo
 * @since 2024/3/11
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    /**
//     * 业务异常
//     */
//    @ResponseStatus
//    @ExceptionHandler(CloudException.class)
//    public Result<?> handleCloudException(CloudException e) {
//        logger.error(e.getMessage(), e);
//        return Result.fail(INTERNAL_SERVER_ERROR.value(), e.getMessage());
//    }

    /**
     * 业务异常（会catch掉异常，不打印异常）
     */
    @ExceptionHandler(CloudException.class)
    public ResponseEntity<?> handleCloudException(CloudException e) {
        logger.error(e.getMessage(), e);
        // 结构体
        Map<String, Object> result = Maps.newLinkedHashMapWithExpectedSize(4);
        result.put("code", e.getCode());
        result.put("msg", e.getMessage());
        result.put("path", RequestUtil.getRequestPath());
        result.put("timestamp", new Date());

        return ResponseEntity.status(e.getCode()).body(result);
    }

}
